/**
 * 
 */
package blms.system.util;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.PropertyUtils;

import blms.system.exception.UnknownAttribute;

/**
 * This class provides a service to access and assign data from/to beans.
 *  
 * @author thiago
 */
public class ReflectionHelper {

	/**
	 * Access java bean's field.
	 * 
	 * @param bean The java bean
	 * @param attribute The name of the field, the bean must be well formatted.
	 * 						If the field name is foo then a getFoo method should be
	 * 						provided by the bean.
	 * 
	 * @return A string vision of the java bean's field 
	 * @throws UnknownAttribute This exception will be throwed when there is a programming error,
	 * 								the bean should be declare well formatted get methods.
	 * 							
	 */
	public String getAttribute(Object bean, String attribute) throws UnknownAttribute {
		
		try {
			return PropertyUtils.getProperty(bean, attribute).toString();
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new UnknownAttribute();
		}
	}
	
	/**
	 * Assign a value to bean's fields.
	 * 
	 * @param bean The java bean
	 * @param attribute	The name of the field, the bean must be well formatted.
	 * 						If the field name is foo then a setFoo method should be
	 * 						provided by the bean.
	 * 
	 * @param attributeValue The new value.
	 * @throws UnknownAttribute	This exception will be throwed when there is a programming error,
	 * 								the bean should be declare well formatted set methods.
	 */
	public void setAttribute(Object bean, String attribute, Object attributeValue) throws UnknownAttribute {

		try {
			PropertyUtils.setProperty(bean, attribute, attributeValue);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e.getCause().getMessage());
		} catch (NoSuchMethodException e) {
			throw new UnknownAttribute();
		}
	}
}
